/*
 * Copyright 2009 André Luiz Alves Moraes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * */


package org.alamoraes.codegen.fileservices;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.alamoraes.codegen.AmCodeGenConsts;
import org.alamoraes.codegen.IFileBackupService;
import org.alamoraes.codegen.ISystemProperties;

/**
 *
 * @author andre
 */
public class FileBackupService implements IFileBackupService {
    
    /**
     * Creates a backup of the file in the sub-directory codegen-bkps.
     * @param f
     */
    public boolean makeBackup(File f) {
        if (!f.isFile())
            return false;

        File container = f.getParentFile();
        File bkpFolder = new File(container, AmCodeGenConsts.getObjectFactory().getInstance(ISystemProperties.class).getBackupFolderName());

        if (bkpFolder.isFile())
            throw new IllegalArgumentException("The backup folder " + bkpFolder.getAbsolutePath() + " already exists and is not a directory");

        if (!bkpFolder.isDirectory()) {
            bkpFolder.mkdirs();
        }

        File bkpFile = new File(bkpFolder,f.getName() + ".bak");
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(f);
            fos = new FileOutputStream(bkpFile);

            /** copy and close the file stream */
            copyStreams(fis, fos, true);
            return true;
        }catch(IOException ioe) {
            return false;
        }
    }

    public void copyStreams(InputStream is, OutputStream os, boolean autoClose) throws IOException {
        byte[] buffer = new byte[4096];
        int dataRead = -1;

        try {
            while((dataRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, dataRead);
            }

            if (autoClose) {
                is.close();
                os.close();
            }
        } catch(IOException ioe) {
            if (autoClose) {
                /** close both streams */
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
            }
            /** re throws the exception for future handling */
            throw ioe;
        }
    }
}
